package com.moviemetagetter.http;

import java.util.ArrayList;
import java.util.StringTokenizer;

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethodBase;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;

public class HTTPHelper {

	public static ArrayList<String> cookies = new ArrayList<String>();
	public static String userAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; InfoPath.3)";
	public static Header[] headers;

	protected static final String post(String url, NameValuePair[] parameters,String referrer) {
		String response = null;

		try {
			HttpClient client = new HttpClient();
			PostMethod method = new PostMethod(url);

			method.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
			method.setRequestHeader("User-Agent", userAgent);
			method.setRequestHeader("Accept-Language", "en-IE");
			method.setRequestHeader("Accept-Encoding", "gzip, deflate");
			method.setRequestHeader("Accept", "image/jpeg, application/x-ms-application, image/gif, application/xaml+xml, image/pjpeg, application/x-ms-xbap, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*");

			if(referrer != null){
				method.setRequestHeader("Referer", referrer);
			}
			
			System.out.println("Making POST request to " + url);

			setCookies(method);

			// Configure the parameters
			if (parameters != null) {
				for (int a = 0; a < parameters.length; a++) {
					method.addParameter(parameters[a].getName(), parameters[a].getValue());
				}
			}

			int statusCode = client.executeMethod(method);

			System.out.println("Response code : " + statusCode);

			if (statusCode != -1) {
				headers = method.getResponseHeaders();
				response = method.getResponseBodyAsString();

				saveCookies(headers);
				method.releaseConnection();
			} else {
				return null;
			}
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println(e.getMessage());
			clearCookies();
			return response;
		}
		return response;
	}

	public static String get(String url,String referrer) {
		String response = null;
		try {
			HttpClient client = new HttpClient();
			GetMethod method = new GetMethod(url);

			method.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
			method.setRequestHeader("User-Agent", userAgent);
			method.setRequestHeader("Accept-Language", "en-IE");
			method.setRequestHeader("Accept-Encoding", "gzip, deflate");
			method.setRequestHeader("Accept", "image/jpeg, application/x-ms-application, image/gif, application/xaml+xml, image/pjpeg, application/x-ms-xbap, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*");

			if(referrer != null){
				method.setRequestHeader("Referer", referrer);
			}

			setCookies(method);

			int statusCode = client.executeMethod(method);

			System.out.println("Response code : " + statusCode);

			if (statusCode != -1) {
				headers = method.getResponseHeaders();
				response = method.getResponseBodyAsString();

				saveCookies(headers);
				method.releaseConnection();
			}
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println(e.getMessage());
			clearCookies();
			return null;
		}

		return response;
	}

	private static void saveCookies(Header[] headers) {
		for (int a = 0; a < headers.length; a++) {
			String key = headers[a].getName();
			String value = headers[a].getValue();

			if (key.equalsIgnoreCase("set-cookie")) {
				StringTokenizer st = new StringTokenizer(value, ";");
				String aCookie = st.nextToken();
				cookies.add(aCookie);
			}
		}
	}

	private static void setCookies(HttpMethodBase method) {
		String total = "";

		for (int a = 0; a < cookies.size(); a++) {
			String cookie = cookies.get(a);
			total = total + cookie + ";";
		}

		if (total != null && !total.equals("")) {
			total = total.substring(0, total.length() - 1);
			method.addRequestHeader("Cookie", total);
		}
	}

	public static void clearCookies() {
		cookies.clear();
	}
	
	public static String getLocationHeaderValue(){
		for(Header header : headers){
			if(header.getName().equalsIgnoreCase("location")){
				return header.getValue();
			}
		}
		
		return null;
	}
}
